/*
 * @Author: 谭必清
 * @Date: 2024-09-06 14:58:57
 * @LastEditors: 谭必清
 * @LastEditTime: 2024-09-06 15:14:48
 * @FilePath: /message-board/js/todo.js
 * Copyright (c) 2020 - 2024 by TanBQ., All Rights Reserved.
 */
/** 处理表格逻辑 */
// 获取最外面的container
const container = document.querySelector('.container')
// 拖拽的哪个元素
let sourceNode
// 跟踪按钮是否可用
let isButtonEnabled = true;

// 开始拖拽
container.ondragstart = function (e) {
    // 默认是copy,通过dataset设置默认效果
    e.dataTransfer.effectAllowed = e.target.dataset.effect
    sourceNode = e.target
}

// 经过哪个元素
container.ondragover = function (e) {
    e.preventDefault()
    // console.log('打印***e.target', e.target)
}

// 清除元素的背景颜色
function clearDropStyle() {
    document.querySelectorAll('.drop-over').forEach(node => {
        node.classList.remove('drop-over')
    })
}

function getDropNode(node) {
    while (node) {
        if (node.dataset && node.dataset.drop) {
            return node
        }
        // 否则向上查找
        node = node.parentNode
    }
}

// 放在哪个元素上方
container.ondragenter = function (e) {
    // 需要清除之前的drop-over
    clearDropStyle()
    // 添加背景颜色，需要判断dataset属性为copy并且是不是等于拖拽元素的e.dataTransfer.effectAllowed 
    const dropNode = getDropNode(e.target)
    if (dropNode && dropNode.dataset.drop === e.dataTransfer.effectAllowed) {

        dropNode.classList.add('drop-over')
    }
}

// 松手  浏览器有默认行为,阻止拖放
container.ondrop = function (e) {
    // console.log('打印***e.target', e.target)
    // 需要清除之前的drop-over
    clearDropStyle()
    const dropNode = getDropNode(e.target)
    // 目标节点是copy
    if (dropNode && dropNode.dataset.drop === e.dataTransfer.effectAllowed) {
        if (dropNode.dataset.drop === 'copy') {
            // 避免多次添加
            dropNode.innerHTML = ''
            const cloneNode = sourceNode.cloneNode(true)
            cloneNode.dataset.effect = 'move'
            dropNode.appendChild(cloneNode)
        } else {
            // 删除拖拽节点
            sourceNode.remove()
        }
    }
}

// 保存课程表
function saveSchedule() {
    if (!isButtonEnabled) return;

    // 获取所有可放置课程的单元格
    const cells = document.querySelectorAll('.right table tbody td[data-drop="copy"]');

    // 检查是否有任何单元格包含内容
    let hasContent = Array.prototype.some.call(cells, cell => cell.innerHTML.trim() !== '');

    if (hasContent) {
        const schedule = [];
        const rows = document.querySelectorAll('.right table tbody tr');
        rows.forEach(row => {
            const rowData = [];
            row.querySelectorAll('td[data-drop="copy"]').forEach(cell => {
                rowData.push(cell.innerHTML.trim());
            });
            schedule.push(rowData);
        });
        localStorage.setItem('schedule', JSON.stringify(schedule));
        showNotification("课程表已保存!", 3);
    } else {
        // 如果没有内容，则不保存并通知用户
        showNotification("课程表为空，无需保存。", 3);
    }
}

// 加载课程表
function loadSchedule(str = null) {
    if (!isButtonEnabled) return;

    let msg = str || "课程表已加载!";

    const schedule = JSON.parse(localStorage.getItem('schedule'))
    if (schedule) {
        const rows = document.querySelectorAll('.right table tbody tr')
        rows.forEach((row, rowIndex) => {
            row.querySelectorAll('td[data-drop="copy"]').forEach((cell, cellIndex) => {
                cell.innerHTML = schedule[rowIndex][cellIndex]
            })
        })
        showNotification(msg, 3)
    } else {
        showNotification("没有保存的课程表!", 3)
    }
}

// 移除课程表
function removeSchedule() {
    if (!isButtonEnabled) return;

    // 获取所有可放置课程的单元格
    const cells = document.querySelectorAll('.right table tbody td[data-drop="copy"]');
    // 清空这些单元格的内容
    cells.forEach(cell => {
        cell.innerHTML = '';
    });
    localStorage.removeItem("schedule")
    showNotification("课程表已清空!", 3);
}

/** 处理通知逻辑 */
function showNotification(message, duration) {
    const notification = document.getElementById('notification');
    notification.textContent = message;

    // isButtonEnabled = false;

    // 显示通知，并添加slideDown动画
    notification.classList.remove('unshow');
    notification.classList.add('show');

    // 移除之前可能存在的slideDown监听器
    notification.removeEventListener('animationend', onSlideDownEnd);

    // 绑定slideDown动画结束事件
    function onSlideDownEnd() {
        // 延迟2秒后触发slideUp动画
        setTimeout(() => {
            // 移除show类以触发slideUp动画
            notification.classList.remove('show');
            notification.classList.add('unshow');
            isButtonEnabled = true;
        }, duration * 1000);
    }

    notification.addEventListener('animationend', onSlideDownEnd);
}

document.addEventListener("DOMContentLoaded", () => {
    if (localStorage.getItem("schedule")) {
        loadSchedule("本地加载成功");
    }
})

let editdata = document.getElementById("editdata");
editdata.addEventListener("dblclick", () => {
    editdata.contentEditable = true;
});
editdata.addEventListener("focusout", () => {
    editdata.contentEditable = false;
})
